<template>
  <!--同步任务-->
  <el-row style="height:100%">
    <page>
      <pageheader :event="'dataSyncAdd'" :isShow="true">
        数据同步任务
      </pageheader>
      <div class="page-content">
        <el-card class="box-card tag-card">
          <el-row>
            <SearchInput
              style="margin-left: 20px"
              @physSearch="physSearch"
              :searchEvent="'physSearch'"
              :value.sync="keywords"
              :searchText="'请输入关键字'"
              ref="clearText"
            >搜索：
            </SearchInput>
            <span style="margin-left: 20px">状态：</span>
            <el-select v-model="statusCheck" @change="statusChange"
                       size="small" style="width:200px">
              <el-option v-for="item  in statusList" :key="item.value" :label="item.name"
                         :value='item.value'></el-option>
            </el-select>
          </el-row>
          <el-table :data="dataTable" size="small" stripe class="data_sync_table">
            <el-table-column type="expand">
              <template slot-scope="props">
                <el-form label-position="left" inline class="demo-table-expand">
                  <el-form-item label="任务描述">
                    <span>{{ props.row.status_desc }}</span>
                  </el-form-item>
                </el-form>
              </template>
            </el-table-column>
            <el-table-column label="企业名称" prop="company_name" align="center"></el-table-column>
            <el-table-column label="数据开始日期" prop="data_begin_time" align="center"></el-table-column>
            <el-table-column label="数据结束时间" prop="data_end_time" align="center"></el-table-column>
            <el-table-column label="数据分包条数" prop="data_sum" align="center"></el-table-column>
            <el-table-column label="任务获取时间" prop="obtain_time" align="center"></el-table-column>
            <el-table-column label="优先级别" prop="priority" align="center"></el-table-column>
            <el-table-column label="任务标记" prop="task_code" align="center">
              <template slot-scope="scope">{{getTaskCodeName(scope.row.task_code)}}</template>
            </el-table-column>
            <el-table-column label="任务状态" prop="status" align="center" width="128px">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.status == 0">{{getName(0)}}</el-tag>
                <el-tag v-else-if="scope.row.status == 1" type="info">{{getName(1)}}</el-tag>
                <el-tag v-else-if="scope.row.status == 2" type="warning">{{getName(2)}}</el-tag>
                <el-tag v-else-if="scope.row.status == 3" type="warning">{{getName(3)}}</el-tag>
                <el-tag v-else-if="scope.row.status == 4" type="success">{{getName(4)}}</el-tag>
                <el-tag v-else-if="scope.row.status == 5" type="danger">{{getName(5)}}</el-tag>
                <el-tag v-else-if="scope.row.status == 9" type="danger">{{getName(9)}}</el-tag>
              </template>
            </el-table-column>
            <!-- <el-table-column label="任务描述" prop="status_desc" align="center" ></el-table-column> -->
            <el-table-column label="执行数 / 总数" prop="task_end_data_sum" align="center">
              <template slot-scope="scope">
                {{scope.row.task_end_data_sum ? scope.row.task_end_data_sum : ''}} / {{scope.row.plan_data_count ?
                scope.row.plan_data_count : ''}}
              </template>
            </el-table-column>
            <el-table-column label="任务创建时间" prop="created_time" align="center">
              <template slot-scope="scope">{{getDate(scope.row.created_time)}}</template>
            </el-table-column>
            <el-table-column label="任务结束时间" prop="task_end_time" align="center"></el-table-column>
            <el-table-column label="更新时间" prop="updated_time" align="center">
              <template slot-scope="scope">{{getDate(scope.row.updated_time)}}</template>
            </el-table-column>
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <el-button size="small" v-if="scope.row.status == 0" @click="clickIssue(scope.row)">发布</el-button>
                <el-button size="small" type="danger" v-else-if="scope.row.status == 2 || scope.row.status == 3"
                           @click="clickStop(scope.row)">中断
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination background
                         layout="total,sizes,prev,pager,next"
                         @current-change="currentChange"
                         @size-change="sizeChange"
                         :page-sizes="pagination.pageSizes"
                         :page-size.sync="pagination.pageSize"
                         :total="pagination.total"
                         :current-page.sync="pagination.currentPage"
                         class="paging fr">
          </el-pagination>
        </el-card>
        <el-dialog v-dialogDrag :title="dialogTitle+'同步任务'" :visible.sync="isShow" @close="closeDialog('ruleForm')"
                   :modal-append-to-body="false" :close-on-click-modal="false" width="1200px">
          <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="180px">
            <el-form-item label="所属企业名称" prop="company_name" style="width:450px">
              <el-popover
                @show="originalShow"
                placement="bottom"
                width="100%"
                trigger="click">
                <el-table :data="original_dataTable" size="small" ref="originalTable" row-key="id"
                          highlight-current-row @current-change="originalHandleSelectionChange">
                  <el-table-column label="企业名称" prop="company_name" align="center"></el-table-column>
                </el-table>
                <el-pagination background
                               layout="total,sizes,prev,pager,next"
                               @current-change="original_currentChange"
                               @size-change="original_sizeChange"
                               :page-sizes="original_pagination.pageSizes"
                               :page-size.sync="original_pagination.pageSize"
                               :total="original_pagination.total"
                               :current-page.sync="original_pagination.currentPage"
                               class="paging fr">
                </el-pagination>
                <el-button slot="reference" :disabled="!isAdd">{{original_name}}</el-button>
              </el-popover>
            </el-form-item>
            <el-form-item label="数据开始结束时间" prop="data_begin_time" v-if="isAdd">
              <el-date-picker
                v-model="dateArr"
                type="daterange"
                range-separator="至"
                start-placeholder="数据开始日期"
                end-placeholder="数据结束日期">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="数据开始时间" v-else prop="data_begin_time">
              <el-input v-model="ruleForm.data_begin_time" size="small" style="width:450px" :disabled="true"></el-input>
            </el-form-item>
            <el-form-item label="数据结束时间" prop="data_end_time" v-if="!isAdd">
              <el-input v-model="ruleForm.data_end_time" size="small" :disabled="true" style="width:450px"></el-input>
            </el-form-item>
            <el-form-item label="数据分包条数" prop="data_sum">
              <el-input-number v-model="ruleForm.data_sum"
                               size="small" :disabled="!isAdd" :min="10"
                               :step="10"></el-input-number>
            </el-form-item>
            <el-form-item label="优先级别" prop="priority">
              <el-input-number v-model="ruleForm.priority" size="small" :min="0" :disabled="!isAdd"></el-input-number>
            </el-form-item>
            <el-form-item label="任务标记" prop="task_code">
              <el-checkbox-group v-model="ruleForm.task_code" :disabled="!isAdd">
                <el-checkbox v-for="item in taskcodeList" :label="item.code" :key="item.code" >{{item.name}}
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <el-form-item label="创建时间" prop="created_time" v-if="!isAdd">
              <el-input v-model="ruleForm.created_time" size="small" :disabled="true" style="width:450px"></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="isShow = false" size="small">取 消</el-button>
            <!--判断是否显示保存按钮：isDisabled 判断为是否为修改页面 -->
            <el-button type="primary" @click="confirmDialog('ruleForm')" v-if="isAdd" size="small">保 存</el-button>
            <el-button type="primary" @click="issue(ruleForm.id)" v-else size="small">发布任务</el-button>
          </div>
        </el-dialog>
      </div>
    </page>
  </el-row>
</template>
<style lang="scss">
  .page-content {
    .tag-card {
      > .el-card__body {
        > .el-row {
          margin: 20px 0;
        }
      }
    }

    padding: 15px;

    .fr {
      float: right;
    }

    .el-table {
      margin-bottom: 10px;
    }

    .paging {
      margin: 15px;
      height: 28px;
    }

    .data_sync_table {

    }
  }

</style>
<script>
  let moment = require("moment");
  import page from "@/components/page/page";
  import SearchInput from "@/components/sys/assembly/searchinput";
  import pageheader from "@/components/page/pageheader";
  import Cascader from "@/components/sys/assembly/elcascader";

  export default {
    data() {
      let validateCompanyId = (rule, value, callback) => {
        if (!this.isAdd) return callback();
        if (!value) {
          return callback(new Error('请选择企业'));
        } else if (this.ruleForm.company_id == '') {
          return callback(new Error('请选择企业'));
        } else {
          callback();
        }
      };
      let validateDate = (rule, value, callback) => {
        if (!this.isAdd) return callback();
        if(!this.dateArr) return callback()
        let startTime = new Date(this.dateArr[0]).getTime()
        let endTime = new Date(this.dateArr[1]).getTime()
        let overTime = 1000 * 60 * 60 * 24 * 92

        if (endTime - startTime > overTime) {
          return callback(new Error('选择时间不得超过三个月'));
        } else {
          this.ruleForm.data_begin_time = moment(this.dateArr[0]).format('YYYY-MM-DD') + ' 00:00:00';
          this.ruleForm.data_end_time = moment(this.dateArr[1]).format('YYYY-MM-DD') + ' 23:59:59';
          callback();
        }
      }
      let validaTaskCode = (rule, value, callback) => {
        if (!this.isAdd) return callback();
        if(!this.dateArr) return callback()

        if (value.length == 0) {
          return callback(new Error('请至少选择一个任务标记'));
        } else {
          callback();
        }
      }
      return {
        dateArr: [],
        dataTable: [],
        keywords: '',
        original_dataTable: [],    //选择企业
        original_pagination: {
          total: 0,//总条目数
          currentPage: 1,//当前页数
          pageSize: 10,//每页显示条目个数
          pageSizes: [10, 20, 50, 100],//每页显示个数选择器的选项设置
        },//表格分页参数
        original_name: '选择企业',
        pagination: {
          total: 0,//总条目数
          currentPage: 1,//当前页数
          pageSize: 10,//每页显示条目个数
          pageSizes: [10, 20, 50, 100],//每页显示个数选择器的选项设置
        },//表格分页参数
        ruleForm: {
          company_id: '',    //企业ID
          company_name: '',  //企业名称
          synchronize_acc: '',      //对应的同步帐号外键
          data_begin_time: '', //数据开始时间
          data_end_time: '',  //数据结束时间，
          data_sum: 1000,  //数据分包条数
          priority: 0,    //优先级别，数字越大，排名越靠前
          task_code: [],//任务标记
          created_time: '', //创建时间
        },
        taskcodeList: [],
        statusCheck: -2,
        statusList: [
          {
            value: -2,
            name: '全部',
          },
        ],
        dialogTitle: '',  //模态框标题
        isAdd: false,
        isShow: false, //新增/编辑 模态框
        rules: {
          company_name: [{required: true, validator: validateCompanyId, trigger: "blur"}],
          data_begin_time: [{required: false, validator: validateDate, trigger: "blur"}],
          priority: [{required: true, message: "请输入优先级别", trigger: "blur"}],
          data_sum: [{required: true, message: "请输入数据分包条数", trigger: "blur"}],
          task_code: [{required: true, validator: validaTaskCode, trigger: "change"}],
        },//form表单验证
      }
    },
    inject: ["reload"],
    components: {
      page,
      pageheader,
      SearchInput,
      Cascader,//级联选择器组件
    },
    created() {
      this.getTaskCode();
    },
    mounted() {
      //点击新增按钮
      this.$Bus.$on("dataSyncAdd", () => {
        this.isAdd = true;
        this.dialogTitle = '新增';
        this.isShow = true;
      });
    },
    beforeDestroy() {
      this.$Bus.$off('companyChange');
    },
    methods: {
      //得到任务标记列表
      getTaskCode() {
        let url = '/syn/task/record/find-task-code';
        this.taskcodeList = [];
        this.$api.get(url)
        .then(data => {
          let _data = data.data;
          for (let item in data.data) {
            let model = {};
            model.code = item;
            model.name = data.data[item];
            this.taskcodeList.push(model);
          }
          this.getStatus();
        })
        .catch(err => {
          console.log(err);
          this.$Bus.$emit('Loading', false);
        })
      },
      //得到任务标记中文
      getTaskCodeName(code) {
        let arr = this.taskcodeList.filter((x) => {
          return x.code == code;
        });
        let str = arr.length ? arr[0].name : code;
        return str;
      },
      //得到状态列表
      getStatus() {
        let url = '/syn/task/record/find-task-status';
        this.statusList = [{
          value: -2,
          name: '全部',
        }];
        this.$api.get(url)
        .then(data => {
          let _data = data.data;
          let _this = this;
          Object.keys(_data).forEach(function (key) {
            let mode = {
              value: key,
              name: _data[key]
            }
            _this.statusList.push(mode);
          });
          this.getDataList();
        })
        .catch(err => {
          console.log(err);
          this.$Bus.$emit('Loading', false);
        })
      },
      //得到状态名字
      getName(key) {
        let arr = this.statusList.filter(data => {
          return data.value == key;
        })
        return arr[0].name;
      },
      //搜索按钮点击事件
      physSearch(data) {
        this.$Bus.$emit('Loading', true);
        this.keywords = data;
        this.getDataList(this.pagination.currentPage, this.pagination.pageSize, this.keywords);
      },
      //搜索状态改变
      statusChange(data) {
        this.$Bus.$emit('Loading', true);
        this.getDataList(this.pagination.currentPage, this.pagination.pageSize, this.keywords);
      },
      //分页change事件
      currentChange(val) {
        this.$Bus.$emit('Loading', true)
        this.pagination.currentPage = val;
        this.getDataList(this.pagination.currentPage, this.pagination.pageSize, this.keywords)
      },
      //每页显示条目个数change事件
      sizeChange(val) {
        this.$Bus.$emit('Loading', true);
        this.getDataList(this.pagination.currentPage, val, this.keywords)
      },
      getDataList(page = 1, page_size = 10, keywords = '') {
        let url = '/syn/task/record/list?keywords=' + keywords + '&status=' + this.statusCheck + '&page=' + page + '&page_size=' + page_size;
        this.$api.get(url)
        .then(data => {
          if (data == '10001') {
            this.$message.error('无权操作该数据')
            this.$Bus.$emit('Loading', false);
            return
          }
          if (data) {
            let _data = data.data;
            this.dataTable = _data.dataList ? _data.dataList : [];
            this.pagination.total = _data.dataCount;
            this.pagination.currentPage = _data.pageCode;
            this.pagination.pageSize = _data.pageSize;
          } else {
            this.dataTable = [];
          }
          this.$Bus.$emit('Loading', false)
        })
        .catch(err => {
           console.log(err);
          this.dataTable = []
          this.$Bus.$emit('Loading', false)
        });
      },

      //选中企业数据展示
      originalShow() {
        this.getOriginalList(this.original_pagination.currentPage, this.original_pagination.pageSize)
      },
      //获取原始数据列表
      getOriginalList(pageCode = 1, page_size = 10) {
        this.$Bus.$emit("Loading", true);
        let url = '/syn/synchronize/account/list?keywords=&page='
          + pageCode + '&page_size=' + page_size
        this.$api.get(url)
        .then(data => {
          if (data) {
            let _data = data.data
            this.original_dataTable = _data.dataList
            this.original_pagination.total = _data.dataCount;
            this.original_pagination.currentPage = _data.pageCode;
            this.original_pagination.pageSize = _data.pageSize;
            if (this.original_row) {
              this.$refs.originalTable.setCurrentRow(this.original_row);
            }
          }
          this.$Bus.$emit("Loading", false);
        })
        .catch(err => {
          console.log(err);
          this.$Bus.$emit("Loading", false);
        })
      },

      original_sizeChange(val) {
        this.getOriginalList(this.original_pagination.currentPage, val)
      },
      //分页change事件
      original_currentChange(val) {
        this.getOriginalList(val, this.original_pagination.pageSize)
      },
      originalHandleSelectionChange(data) {
        if (data) {
          this.ruleForm.company_id = data.company_id;
          this.ruleForm.synchronize_acc = data.id;
          this.ruleForm.company_name = data.company_name;
          this.original_name = data.company_name;
        }
      },
      //模态框保存按钮
      confirmDialog(formName) {
        let dataV = {};
        let model = null;
        this.$refs[formName].validate(valid => {
          if (valid) {
            // this.$Bus.$emit('Loading',true);
            model = this.$refs[formName].model;
            dataV.company_id = model.company_id;
            dataV.synchronize_acc = model.synchronize_acc;
            dataV.company_name = model.company_name;
            dataV.data_begin_time = model.data_begin_time;
            dataV.data_end_time = model.data_end_time;
            dataV.data_sum = model.data_sum;
            dataV.priority = model.priority;

            let _this = this;
            async function toAdd() {
              for(let i = 0; i < model.task_code.length;i++){
                if(model.task_code[i]){
                  dataV.task_code = model.task_code[i]
                  await _this.confirmAdd(dataV)
                }
              }
              _this.isShow = false
              _this.$message({
                message: "添加完成",
                type: "success"
              });
              _this.getDataList(_this.pagination.currentPage, _this.pagination.pageSize, _this.keywords)
              _this.$Bus.$emit('Loading', false);
            }
            toAdd()
          } else {
            this.$Bus.$emit('Loading', false);
            return false;
          }
        });
      },
      //新增
      confirmAdd(dataV){
        return new Promise(res =>{
          let url='/syn/task/record/create-task-record';
          this.$api.post(url,dataV)
          .then(data=>{
            res()
          })
          .catch(err => {
            res()
          })
        })
      },
      //关闭模态框
      closeDialog(formName) {
        this.$refs[formName].resetFields();
        this.original_name = '选择企业';
        this.original_dataTable = [];
        this.dateArr = [];
        this.$Bus.$emit('Loading', false);
        this.ruleForm = {
          company_id: '',    //企业ID
          company_name: '',  //企业名称
          synchronize_acc: '',      //对应的同步帐号外键
          data_begin_time: '', //数据开始时间
          data_end_time: '',  //数据结束时间，
          data_sum: 1000,  //数据分包条数
          priority: 0,    //优先级别，数字越大，排名越靠前
          task_code: [],//任务标记
          created_time: '', //创建时间
        }
      },
      //发布点击
      clickIssue(row) {
        this.isShow = true;
        this.$Bus.$emit('Loading', true);
        this.isAdd = false;
        this.dialogTitle = ''
        this.getRecord(row.id)
      },

      getRecord(id){
        let url = '/syn/task/record/get?id='+id
        this.$api.get(url)
        .then(data=>{
          let _data = data.data
          if(_data){
            _data.task_code = [_data.task_code];
            _data.created_time= this.getDate(_data.created_time);
            this.original_name = _data.company_name
            console.log(_data,'_data');
            this.ruleForm = Object.assign(this.ruleForm,JSON.parse(JSON.stringify(_data)))
          }
          this.$Bus.$emit('Loading', false);
        })
        .catch(err=>{
          console.log(err);
          this.isShow = false;
          this.$Bus.$emit('Loading', false);
        })

      },
      //中断点击
      clickStop(row) {
        this.$confirm('是否确定中断?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(() => {
          let url = '/syn/task/record/break-of-task?taskRecordId=' + row.id;
          this.$api.get(url)
          .then(data => {
            if (data.code == 0) {
              this.getDataList(this.pagination.currentPage, this.pagination.pageSize, this.keywords)
              this.$message({
                message: "中断成功",
                type: "success"
              });
            } else {
              this.$message({
                message: "中断失败",
                type: "error"
              });
            }
          })
          .catch(err => {
            console.log(row);
          })
        })
        .catch(() => {
        });
      },
      //发布调接口
      issue(id) {
        this.$Bus.$emit('Loading', true);
        let url = '/syn/task/record/publish-task-record?taskRecordId=' + id;
        this.$api.put(url)
        .then(data => {
          if (data.code == 0) {
            this.getDataList(this.pagination.currentPage, this.pagination.pageSize, this.keywords)
            this.isShow = false
            this.$message({
              message: "发布成功",
              type: "success"
            });
          } else {
            this.$message({
              message: "发布失败",
              type: "warning"
            });
          }
          this.$Bus.$emit('Loading', false);
        })
        .catch(err => {
          this.$Bus.$emit('Loading', false);
        })
      },
      //格式化(date)时间
      getDate(date) {
        return date ? moment(date).format('YYYY-MM-DD HH:mm:ss') : '';
      }
    },
    watch: {}
  }
</script>
